package com.cloud.poetry.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.poetry.base.entity.User;
import com.cloud.poetry.base.feign.ChatRoomFeignClient;
import com.cloud.poetry.base.util.BaseUtil;
import com.cloud.poetry.core.entity.ChatCacheUser;
import com.cloud.poetry.core.exception.PoetryException;
import com.cloud.poetry.system.entity.dto.LoginDTO;
import com.cloud.poetry.system.entity.dto.RegisterDTO;
import com.cloud.poetry.system.mapper.UserMapper;
import com.cloud.poetry.system.service.LoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author mengxj
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private ChatRoomFeignClient fileFeignClient;

    @Override
    public void login(LoginDTO login) {
        String loginName = login.getLoginName(), password = login.getPassword();
        LambdaQueryWrapper<User> wrapper = new QueryWrapper<User>().lambda()
                .eq(User::getLoginName, loginName).or()
                .eq(User::getEmail, loginName).or().eq(User::getPhone, loginName);
        User user = this.userMapper.selectOne(wrapper);
        if(Objects.isNull(user)){
            throw new PoetryException("登陆失败：当前用户不存在或密码错误！");
        }
        if(!user.getPassword().equals(password)){
            throw new PoetryException("登陆失败：当前用户不存在或密码错误！");
        }
        BaseUtil.saveUser(user);
        ChatCacheUser cacheUser = new ChatCacheUser();
        BeanUtils.copyProperties(user, cacheUser);
        this.fileFeignClient.addUser(cacheUser);
    }

    @Override
    public void register(RegisterDTO register) {
        String loginName = register.getLoginName();
        LambdaQueryWrapper<User> wrapper = new QueryWrapper<User>().lambda().eq(User :: getLoginName, loginName);
        User user = this.userMapper.selectOne(wrapper);
        if(Objects.nonNull(user)){
            throw new PoetryException(String.format("注册失败：该账号 %s 已被注册，请重新换账号注册！", loginName));
        }
        User u = new User();
        BeanUtils.copyProperties(register, u);
        this.userMapper.insert(u);
    }
}
